package controller.login;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import define.API;
import define.Key;
import ui.activity.login.Login;

/**
 * Created by trek2000 on 19/8/2014.
 */
public class GetCsAccountBySocialMediaAsync extends AsyncTask<String, Void, Boolean> {

    /**
     * String section
     */
    public static int choose_social_media_account = 0;
    public static final int is_facebook_account = 1;
    public static final int is_google_plus_account = 2;

    private String OTP = null;
    private String STATUS = null;
    private String USER_NAME = null;
    private String ACCESS_TOKEN = null;

    /**
     * The others section
     */
    private Context mContext;

    /**
     * @param context
     */
    public GetCsAccountBySocialMediaAsync(Context context) {
        this.mContext = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        return getData(params);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        if (!result) {

        } else {
            Log.i("","GetSocialAcc USER_NAME: " + USER_NAME);
            Log.i("","GetSocialAcc OTP: " + OTP);
            //get user name and access_token server response, then call API login async
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                new LogInAsync(mContext)
                        .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                                USER_NAME, ACCESS_TOKEN,
                                Login.user.getDeviceToken(), Key.ANDROID);
            else
                new LogInAsync(mContext)
                        .execute(
                                USER_NAME, ACCESS_TOKEN,
                                Login.user.getDeviceToken(), Key.ANDROID);
        }
    }

    /**
     * Basic methods
     */

    private boolean getData(String[] params) {
        HttpPost mHttpPost = new HttpPost(API.GET_CS_ACCOUNT_BY_SOCIAL_MEDIA);
        List<NameValuePair> mListValues = new ArrayList<NameValuePair>();
        mListValues.add(new BasicNameValuePair(Key.SOCIAL_ACCOUNT, params[0]));
        mListValues.add(new BasicNameValuePair(Key.SOCIAL_MEDIA, params[1]));
        mListValues.add(new BasicNameValuePair(Key.LOGIN,  params[2]));
        mListValues.add(new BasicNameValuePair(Key.FIRST_NAME, params[3]));
        mListValues.add(new BasicNameValuePair(Key.LAST_NAME, params[4]));
        mListValues.add(new BasicNameValuePair(Key.DEVICE_TOKEN, params[5]));
        mListValues.add(new BasicNameValuePair(Key.DEVICE_OS, params[6]));

        try {
            mHttpPost.setEntity(new UrlEncodedFormEntity(mListValues, "UTF-8"));
            HttpParams mHttpParams = new BasicHttpParams();
            int TIMEOUT_CONNECTION = 30000;
            int TIMEOUT_SOCKET = 30000;
            HttpConnectionParams.setConnectionTimeout(
                    mHttpParams, TIMEOUT_CONNECTION);
            HttpConnectionParams.setSoTimeout(mHttpParams, TIMEOUT_SOCKET);
            HttpClient mHttpclient = new DefaultHttpClient(mHttpParams);
            HttpResponse mHttpResponse;
            mHttpResponse = mHttpclient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            String XML = EntityUtils.toString(mHttpEntity);

            Log.i("", GetCsAccountBySocialMediaAsync.class.getSimpleName() + " " + XML);

            // read JSon: get string object State, msg in J-son XML
            JSONObject mJoXml = new JSONObject(XML);
            /**
             * otp
             * status
             * username
             */
            //get string from xml json object
            OTP = mJoXml.getString(Key.OTP);
            USER_NAME = mJoXml.getString(Key.USERNAME);
            ACCESS_TOKEN = mJoXml.getString(Key.ACCESS_TOKEN);

            STATUS = mJoXml.getString(Key.STATUS);
            if (STATUS.equals("Success")) return true;
        } catch (ClassCastException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}